<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
use app\admin\model\ClientUsers;

class ClientUser extends Base {

    private $table = 'ClientUsers';

    public function index(){
        $where = [];
        $search = trim(input('get.search'));
        $search && $where['nickname|mobile'] = ['LIKE', "%$search%"];
        $status = input('get.status');
        is_numeric($status) && $where['status'] = $status;
        $note = input('get.note');
        is_numeric($note) && $where['note'] = $note;
        if(input('get.is_explode')){
            $users_list = db('users')->where($where)->field('nickname,mobile')
                ->order("id","desc")->select();
            $this->export_user_list('用户列表'.date('Y年m月d H时i分'), ['昵称', '电话'], $users_list);
            exit();
        }
        $fieldsArr = [
            "id","avatar",'nickname',"name","mobile","status","birthday",
            "sex","points","is_verification","openid","number",'first_weight','verification_time','note'
        ];
        $users = model($this->table)->where($where)->field($fieldsArr)
            ->order("id","desc")->paginate('',false,page_param());
        $this->assign("data",$users);
        $this->assign("userStatuslist", ClientUsers::$user_status);
        $this->assign("user_note", ClientUsers::$user_note); //开盘通知
        return $this->fetch();
    }

    public function edit(Request $request){
        if($request->isPost()){
            return $this->store($request);
        }
        $id = input("route.id",0);
        $where = [
            "id" => $id,
        ];
        $user = model("ClientUsers")
            ->where($where)
            ->find();
        $this->assign("info",$user);
        $this->assign("user_status", ClientUsers::$user_status);
        return $this->fetch();
    }

    private function store(Request $request){
        $params =   $request->only(["id","error_msg","status",'first_weight']);
        model("ClientUsers")->isUpdate(true)->save($params);
        return $this->ajaxReturn(0,'',url('ClientUser/index'));
    }

    //删除用户
    public function delete(Request $request){
        $params =   [
            "id"    =>  input("post.id/d",0),
        ];
        model("ClientUsers")->where($params)->delete();
        return $this->ajaxReturn();
    }

    /**
     * @param $filename 导出文件名
     * @param array $tileArray  列名
     * @param array $dataArray  列数据
     */
    public  function export_user_list($file_name, $tileArray, $dataArray){
        ini_set('memory_limit','512M');
        ini_set('max_execution_time',0);
        require EXTEND_PATH.'PHPExcel1.8/Classes/PHPExcel.php';
        $excel=new \PHPExcel();
        $letter = array('A','B');
        $tableheader = $tileArray;
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
            $excel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth(20);
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(14);
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        $data=$dataArray;
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                $excel->getActiveSheet()->getStyle("$letter[$j]$i")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->getStyle("$letter[$j]$i")->getFont()->setSize(14);
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$file_name.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
    }

    /**
     * 用户积分记录
     * @return mixed
     */
    public function user_points_log_index(){
        $params = input('get.');
        $where = [];
        if(isset($params['type'])){
            $params['type'] && $where['upl.type'] = $params['type'];
        }
        if(isset($params['search'])){
            $search = trim($params['search']);
            $search && $where['u.nickname'] = ['LIKE', "%$search%"];
        }
        $field = ['upl.*', 'u.nickname'];
        $list = model('user_points_log')->alias('upl')
            ->join('users u', 'upl.user_id=u.id')->field($field)->where($where)
            ->order('upl.id desc')->paginate('',false,page_param());
        $this->assign('data', $list);
        $this->assign('points_type', \app\admin\model\UserPointsLog::$points_type);
        return $this->fetch();
    }

    /**
     * 用户称重记录
     * @return mixed
     */
    public function user_weight_log_index(){
        $params = input('get.');
        $where = [];
        if(isset($params['search'])){
            $search = trim($params['search']);
            $search && $where['u.nickname'] = ['LIKE', "%$search%"];
        }
        $field = ['u.nickname', 'u.id'=>'user_id', 'uwl.id', 'uwl.weight', 'uwl.create_time'];
        $list = db('user_weight_log')->alias('uwl')
            ->join('users u', 'u.id=uwl.user_id')->field($field)
            ->where($where)->order('uwl.id desc')->paginate('',false,page_param());
        $this->assign('data', $list);
        return $this->fetch();
    }

    // 添加称重记录
    public function user_weight_log_add(){
        if(request()->isPost()){
            $data = input('post.');
            if(!$data['weight']){
                return $this->ajaxReturn(1,'请输入体重');
            }
            $err = 0; // 1失败  0成功
            $info = Db::table('users')->where('id', $data['user_id'])
                ->field('first_weight, last_weight')->find();
            Db::startTrans();
            try{
                $update_user = [];
                $now_time = time();
                $log_data['user_id'] = $data['user_id'];
                $log_data['type'] = 5;
                $is_first = 0; // 0第一次登陆
                if($info['first_weight']>0 && $info['last_weight']>0){
                    $update_user['last_weight'] = $data['weight'];
                    $is_first = 1;
                }else{
                    $update_user['first_weight'] = $data['weight'];
                    $update_user['last_weight'] = $data['weight'];
                }
                if($is_first){
                    // 当前体重是否大于第一次体重 这个称重逻辑聂光磊懂
                    if($data['weight'] > $info['first_weight']){
                        if($info['last_weight'] < $info['first_weight']){
                            $update_integral = ($info['first_weight']-$info['last_weight']) * 10;
                            if($update_integral > 0){
                                $update_integral *= -1;
                            }
                        }
                    }elseif($data['weight'] <= $info['first_weight']){
                        if($info['last_weight'] < $info['first_weight']){
                            $update_integral = ($info['last_weight']-$data['weight'])*10;
                        }elseif($info['last_weight'] >= $info['first_weight']){
                            $update_integral = ($info['first_weight']-$data['weight'])*10;
                        }
                        if(isset($update_integral)){
                            if($info['last_weight'] > $data['weight']){
                                $update_integral = abs($update_integral);
                            }elseif($info['last_weight'] < $data['weight']){
                                $update_integral = abs($update_integral) * (-1);
                            }
                        }
                    }
                }
                Db::table('users')->where('id', $data['user_id'])->update($update_user);
                Db::table('user_weight_log')->insert(['user_id'=>$data['user_id'], 'weight'=>$data['weight'], 'create_time'=>$now_time]);
                if(isset($update_integral)){
                    $abs_update_integral = abs($update_integral);
                    if($update_integral > 0){
                        $log_data['desc'] = '减肥成功获取积分';
                        $log_data['status'] = 1;
                        Db::table('users')->where('id', $data['user_id'])->setInc('points', $abs_update_integral);
                    }elseif($update_integral < 0){
                        $log_data['desc'] = '减肥失败扣除积分';
                        $log_data['status'] = 2;
                        Db::table('users')->where('id', $data['user_id'])->setDec('points', $abs_update_integral);
                    }
                    $log_data['points'] = $abs_update_integral;
                    $log_data['create_time'] = $now_time;
                    Db::table('user_points_log')->insert($log_data);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $err = 1;
            }
            $err ? $msg='提交失败' : $msg='提交成功';
            return $this->ajaxReturn($err, $msg);
        }else{
            $this->assign('user_id', input('get.user_id'));
            return $this->fetch();
        }
    }

    // 用户称重图表
    public function user_weight_log_echarts(){
        $id = input('id');
        $data = db('user_weight_log')->where('user_id', $id)->field('weight,create_time')->select();
        $times = array_column($data, 'create_time');
        foreach ($times as $k=>$v){
            $times[$k] = date('Y/m/d', $times[$k]);
        }
        $this->assign('times', json_encode($times));
        $this->assign('weights', json_encode(array_column($data, 'weight')));
        return $this->fetch();
    }

    /**
     * 邀请见证
     * @return mixed
     */
    public function user_witness(){
        $params = input();
        $where = [];
        if(isset($params['status']) && is_numeric($params['status'])){
            $where['w.status'] = $params['status'];
        }
        if(isset($params['examine']) && is_numeric($params['examine'])){
            $where['w.examine'] = $params['examine'];
            dump(777);
        }
        if(isset($params['search'])){
            $search = trim($params['search']);
            $search && $where['u.nickname|u.mobile'] = ['LIKE', "%$search%"];
        }
        $field = ['w.*', 'u.nickname', 'u.mobile'];
        $list = model('witness')->alias('w')
            ->join('users u', 'w.user_id=u.id')->where($where)
            ->field($field)->order('w.id desc')->paginate('',false,page_param());
        $this->assign('data', $list);
        return $this->fetch();
    }

    public function user_witness_edit(){
        $params = input();
        $field = ['w.*', 'u.nickname'];
        $info = model('witness')->alias('w')
            ->join('users u', 'w.user_id=u.id')
            ->field($field)->where('w.id', $params['id'])->find();
        $user_witness = db('user_witness')->alias('uw')
            ->join('users u', 'u.openid=uw.openid')
            ->where('witness_id',$info->id)->field(['uw.nick', 'u.id'])->select();
        $this->assign('info', $info);
        $this->assign('user_witness', $user_witness);
        return $this->fetch();
    }

    public function witness_edit_save(){
        $data = input('');
        $is_save = db('witness')->where('id',$data['id'])->find();
        if($is_save['examine'] > 0){
            return $this->ajaxReturn(1, '禁止重复修改');
        }
        $res = db('witness')->where('id',$data['id'])->update($data);
        if($res){
            $examine = \app\admin\model\Witness::$witness_examine; // 审核状态
            $mobile = db('users')->where(['id'=>$is_save['user_id']])->value('mobile');
            if($mobile){
                \app\api\logic\UserLogic::sendSms($mobile, $examine[$data['examine']]);
            }
            return $this->ajaxReturn(0, '操作成功', url('user_witness'));
        }else{
            return $this->ajaxReturn(1, '操作失败');
        }
    }

    public function user_witness_del(){
        if(request()->isPost()){
            $r = model('witness')->where('id', input('post.id'))->delete();
            if($r){
                return $this->ajaxReturn(0, '操作成功', url('user_witness'));
            }else{
                return $this->ajaxReturn(1, '操作失败');
            }
        }
    }

}
